from datetime import datetime
import json
import random, re
import time

# import datetime

import redis
from django.http import HttpResponse
from flask import Blueprint, jsonify, request, make_response
from flask_restful import reqparse, Api

from utils.MySms import SmsTool
from utils.myredis import r
from utils.db import db
from utils.MyJwt import JwtTool
from utils.captcha.captcha import captcha
from utils.snowflake import IdWorker
from utils.rewrite import DateEncoder

animal_bp = Blueprint('animal_bp', __name__, url_prefix='/animal')
api = Api(animal_bp)


# 添加照片
@animal_bp.route('/img', methods=['POST'])
def img():
    img = request.files.get("img")
    print('>>>', img)

    # 获取图片的后缀名
    # img.filename 当前图片的地址
    ext = img.filename.split('.')[-1]

    # 获取时间戳并拼接
    now_time = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
    print("时间", now_time)

    new_time = "%s%s.%s" % (now_time, random.randint(100, 999), ext)
    print("文件名", new_time)

    # 拼接路由保存到本地
    save_path = "static/img/%s" % new_time
    img.save(save_path)

    return jsonify({
        "code": 200,
        "msg": "上传成功",
        'img': save_path
    })


# 发布宠物
@animal_bp.route('/addmyxunchong', methods=['POST'])
def addmyxunchong():
    req = reqparse.RequestParser()
    req.add_argument("variety", required=True)
    req.add_argument("sex", required=True)
    req.add_argument("age", required=True)
    req.add_argument("time", required=True)
    req.add_argument("location", required=True)
    req.add_argument("contact_way", required=True)
    req.add_argument("conditions", required=True)
    req.add_argument("img")
    req.add_argument("user_id")
    # req.add_argument("state", type=int, required=True)
    args = req.parse_args()


    # 生成雪花算id
    code = IdWorker().get_id
    print("雪花算法id：", code)
    # 进行hash分表添加
    num = code % 3
    table_name = "seek_avour" + str(num)
    print(table_name)

    code0 = 0
    time = r.get_str("code0")
    if time:
        code0 = time
    print("11111111111111", code0)

    if code < int(code0):
        r.del_str("code0")
        r.set_str("code0", code)
        return jsonify({
            "code": 200,
            "msg": "时钟回拨"
        })

    sql = "insert into %s(variety, sex, age, time, location, contact_way, conditions, img, code, user_id, state) values ('%s', '%s','%s','%s','%s','%s','%s', '%s','%s', '%s',%d)" % (
    table_name, args['variety'], args['sex'], args['age'], args['time'], args['location'], args['contact_way'],
    args['conditions'], args['img'], code, args['user_id'], 1)
    print(sql)
    db.update(sql)
    db.commit()

    r.set_str("code0", code)
    # key = "xunchong"
    # r.set_str(key, json.dumps(animal_info, cls=DateEncoder), 3600)

    return jsonify({
        "code": 200,
        "msg": "发布成功"
    })


# # 展示分页优化发布的宠物
# @animal_bp.route('/getmyxunchong')
# def getmyxunchong():
#     req = reqparse.RequestParser()
#     req.add_argument('page')  # 当前第几页
#     args = req.parse_args()
#     page = args['page']
#     page_size = 2  # 每页条数
#
#     # 加入分布式锁
#     key = r.get_str("page_" + args['page'])
#     if not key:
#         print("smjjjjjjjjjjjjjjjjjjjjjj")
#
#         for i in range(1, 6):
#             print(i)
#             statr = (int(page) - 1) * page_size
#             sql = "SELECT * FROM (SELECT * FROM seek_avour0 UNION ALL SELECT * FROM seek_avour1 UNION ALL SELECT * FROM seek_avour2)AS a LEFT JOIN (SELECT id,NAME FROM USER)AS b ON a.user_id = b.id limit %d,%d" % (statr, page_size)
#             res = db.find_all(sql)
#             print("11111111", res)
#
#             key ='page_'+ str(page)
#             print(key)
#
#             r.set_str(key, json.dumps(res, cls=DateEncoder), 3600)
#             page = int(page)+1
#         return jsonify({
#             "code": 200,
#             "msg": "获取成功",
#             "data": json.loads(key)
#         })
#     else:
#         print("xmjjjjjjjjjjjjjjj")
#         return jsonify({
#             "code": 200,
#             "data": json.loads(key)
#         })


# # 展示分页优化加分布式锁发布的宠物
# @animal_bp.route('/getmyxunchong')
# def getmyxunchong():
#     req = reqparse.RequestParser()
#     req.add_argument('page')  # 当前第几页
#     args = req.parse_args()
#
#     page = args['page']
#     page_size = 2  # 每页条数
#
#     key = 'page_' + str(page)
#     print(key)
#     res = r.get_str(key)
#
#     # 加入分布式锁
#     r.setnx_str("name", "1")
#     resp = r.get_str("name")
#     if resp is not None:
#         print("smjjjjjjjjjjjjjjjjjjjjjj")
#         for i in range(1, 6):
#             print(i)
#             statr = (int(page) - 1) * page_size
#             sql = "SELECT * FROM (SELECT * FROM seek_avour0 UNION ALL SELECT * FROM seek_avour1 UNION ALL SELECT * FROM seek_avour2)AS a LEFT JOIN (SELECT id,NAME FROM USER)AS b ON a.user_id = b.id limit %d,%d" % (statr, page_size)
#             animal_info = db.find_all(sql)
#             print("1111111111", animal_info)
#
#             r.set_str(key, json.dumps(animal_info, cls=DateEncoder), 3600)
#             page = int(page)+1
#
#         r.del_str("name")
#         return jsonify({
#             "code": 200,
#             "msg": "获取成功",
#             "data": json.loads(str(res))
#         })
#
#     if res is not None:
#         print("xmjjjjjjjjjjjjjjj")
#         return jsonify({
#             "code": 200,
#             "data": json.loads(str(res))
#         })




# 没有做分页，使用分布式锁
@animal_bp.route('/getmyxunchong')
def getmyxunchong():
    key = "xunchong"
    resd = r.get_str(key)

    # 先查询缓存 存在的话转换成json格式输出
    if resd is not None:
        print("redis不为空")
        # 转换json格式
        data = json.loads(resd)
        return jsonify({"code": 200, "data": data})

    # 加入分布式锁
    r.setnx_str('name', '1')
    resp = r.get_str('name')
    if resp is not None:
        print("redis为空")
        # 取出来全部数据
        sql = " select * from (select * from seek_avour0 union all select * from seek_avour1 union all select * from seek_avour2)as a left join (select id,NAME,img as user_img from user)as b on a.user_id = b.id"
        animal_info = db.find_all(sql)
        # 查出来后，加入缓存中
        r.set_str(key, json.dumps(animal_info, cls=DateEncoder), 3600)
        r.del_str("name")

        return jsonify({
            "code": 200,
            "msg": "查看寻宠",
            "data": animal_info
        })






# 添加我的宠物
@animal_bp.route('/addmypet', methods=['POST'])
def addmypet():
    req = reqparse.RequestParser()
    # req.add_argument("img", required=True)
    req.add_argument("name", required=True)
    req.add_argument("sex", required=True)
    req.add_argument("variety", required=True)
    req.add_argument("birthday", required=True)
    req.add_argument("jy", required=True)
    req.add_argument("bz", required=True)
    req.add_argument("user_id")
    args = req.parse_args()

    sql = "insert into my_pet(name, sex, variety, birthday, jy, bz, user_id) values ('%s','%s','%s','%s','%s','%s','%s')" % (
    args['name'], args['sex'], args['variety'], args['birthday'], args['jy'], args['bz'], args['user_id'])
    db.update(sql)
    db.commit()

    return jsonify({
        "code": 200,
        "msg": "添加我的宠物成功"
    })


# 查看我的宠物
@animal_bp.route('/getmypet')
def getmypet():
    user_id = request.args.get("user_id")
    sql = "select * from my_pet where user_id=%s" % (user_id)
    mypet_info = db.find_all(sql)

    return jsonify({
        "code": 200,
        "msg": "查看我的宠物成功",
        "data": mypet_info
    })
